// pickCardLog.js
var Zan = require('../../css/index')

var date = new Date();
var year = date.getFullYear();
var foreYear = year;
var month = date.getMonth() + 1;
var foreMonth = month - 1;
if (foreMonth == 0) {
  foreMonth = 12;
  foreYear = year - 1;
}
var day = date.getDate();
if (month < 10) {
  month = '0' + month;
}
if (foreMonth < 10) {
  foreMonth = '0' + foreMonth;
}
if (day < 10) {
  day = '0' + day
}
var now = year + '-' + month + '-' + day;
var start = foreYear + '-' + foreMonth + '-' + day;
var app = getApp();

Page(Object.assign({}, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    nameFocus: false,
    cardNumFocus: false,
    stuNumFocus: false,
    pickerNameFocus: false,
    pickerPhoneFocus: false,
    startDay: start,
    pickDate: now,    
    endDay: now,
    canPlay: false,
    placePicker: {
      place: ['请选择', '图书馆前台', '修远书院前台', '敬一书院前台', '明德书院前台', '研究生宿舍前台', '德馨书院前台', '至诚书院前台', '弘毅书院前台', '知行书院前台', '思源书院前台'],
      iniVal: 0,
    },
    placeChoice: 0,
    cardPlace: '',
    way: 1, //作为哪种方式 0： 选择地点 1：私下联系

    lostCardInfo: {
      name: '',
      num: '',
      stuNum: '',      
    },
    pickerInfo: {
      name: '',
      phone: '',
    },
    update:0,
    oldCardNum:'', //修改信息时，要附上原本的cardNum以便修改
    needChange:false,
    submitDisable:false,
  },
  onLoad: function(options) {
    var that = this;
    var initInfo={}; 
    var data;
    if (options.needChange == '1') {
      this.setData({ update: 1,needChange:true });
      wx.request({
        url: app.globalData.baseUrl + '/getPickCardLog',
        data: {
          openid: app.globalData.openid
        },
        success: function(res) {
          data = res.data;
          var item = [];

          if (res.data['count'] == 0) {
            wx.showToast({
              title: '您尚未进行捡卡登记或登记信息已过时',
              icon: 'none'
            });
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              })
            }, 1000);
          } else { // if has log   
                    
            if (res.data['count'] == 1) {              
              initInfo = Object.assign({}, data['result'][0]);
              var cardInfo = {
                name: initInfo['name'],
                num: initInfo['cardNum'],
                stuNum: initInfo['stuNum']
              }
              wx.showLoading({
                title: '请稍后',
                mask: true
              })
              that.setData({ lostCardInfo: cardInfo });
              if (initInfo['place'] != null) {
                that.setData({
                  way: 0,
                  'placePicker.iniVal': parseInt(initInfo['place'])
                });              
              }
              else {
                that.setData({
                  way: 1,
                  'pickerInfo.name': initInfo['pickerName'],
                  'pickerInfo.phone': initInfo['pickerPhone'],
                })
              }
              setTimeout(function () { that.setData({ canPlay: true, oldCardNum: initInfo['cardNum'] }); wx.hideLoading() }, 1000) 
            } 
            else { //如果有多个有效捡卡记录
              var count = data['result'].length;
              console.log(data['result'])
              for (var i = 0; i < count; i++) {
                item[item.length] = ('卡号：' + data['result'][i]['cardNum'])
              }
              wx.showActionSheet({
                itemList: item,
                success: function(res) {
                  initInfo = JSON.parse(JSON.stringify(data['result'][res.tapIndex]));      
                  var cardInfo = {
                    name: initInfo['name'],
                    num: initInfo['cardNum'],
                    stuNum: initInfo['stuNum']
                  }
                  wx.showLoading({
                    title: '请稍后',
                    mask: true
                  })
                  that.setData({ lostCardInfo: cardInfo });
                  if (initInfo['place'] != null) {
                    that.setData({
                      way: 0,
                      'placeChoice': parseInt(initInfo['place'])
                    });
                  }
                  else {
                    that.setData({
                      way: 1,
                      'pickerInfo.name': initInfo['pickerName'],
                      'pickerInfo.phone': initInfo['pickerPhone'],
                    })
                  }
                  setTimeout(function () { that.setData({ canPlay: true ,oldCardNum:initInfo['cardNum']});wx.hideLoading() }, 1000)                                       
                }, 
                fail:function(){wx.navigateBack({
                  delta:1
                })}            
              })
              
            }                                    
          }

        }
      })
    } //if end 
    else {
      this.setData({
        canPlay: true
      });
    }//else end
  },//onLoad end


  radioChange: function(e) {

    this.setData({
      way: e.detail.value
    });
  },

  onAreaChange: function(e) {
    this.setData({
      collegeChoice: e.detail.value
    })
  },

  onPlaceChange: function(e) {
    this.setData({
      placeChoice: e.detail.value
    })
    // this.data.flag=1;
  },

  startDateChange: function(e) {
    // console.log(e.detail);
    this.setData({
      pickDate: e.detail.value
    });
  },
  //检测用户输入是否规范
  // submit:function(e){
  //   let formId=e.detail.formId;

  // }
  submit: function(e) {
    let value = e.detail.value;
    let checkStuN = /^[0-9]{5,10}$/;
    let checkCardN = /^0[0-9]{5}$/;
    let checkPhoneNum = /^[186][0-9]{4,10}$/
    var formId = e.detail.formId;
    if (value.cardName.length == 0 ) {
      this.showZanTopTips('请输入卡主姓名');
      this.setData({
        nameFocus: true
      })
      return;
      //todo:add auto-focus
    }
    if (value.cardName.length > 4) {
      this.showZanTopTips('姓名有误，请重新输入');
      this.setData({ nameFocus: true });
      return;
    }
    this.data.lostCardInfo.name = value.cardName;
    this.setData({
      nameFocus: false
    })

    if (!checkCardN.test(value.cardNum)) {
      this.showZanTopTips('卡号输入有误');
      this.setData({
        cardNumFocus: true
      })

      return;
    }
    this.data.lostCardInfo.num = value.cardNum;
    this.setData({
      cardNumFocus: false
    })


    if (!checkStuN.test(value.stuNum)) {
      this.showZanTopTips('学号输入有误');
      this.setData({
        stuNumFocus: true
      })

      return;
    }
    this.data.lostCardInfo.stuNum = value.stuNum;
    this.setData({
      stuNumFocus: false
    })

    // this.data.lostCardInfo.college = this.data.collegePicker.college[this.data.collegeChoice]
    if (this.data.way == 0) {
      // this.data.cardPlace = this.data.placePicker.place[this.data.placeChoice]
      if (this.data.placeChoice == 0) {
        this.showZanTopTips('请选择放卡位置');
        return;
      }
    } else {
      if (value.pickerName.length == 0 ) {
        this.showZanTopTips('请输入您的昵称');
        this.setData({
          pickerNameFocus: true
        })
      
        return;
      }
      if ( value.pickerName.length > 5){
        this.showZanTopTips('昵称长度过长');
        this.setData({
          pickerNameFocus: true
        })

        return;
      }
      this.data.pickerInfo.name = value.pickerName
      this.setData({
        pickerNameFocus: false
      })

      if (!checkPhoneNum.test(value.pickerPhone)) {
        this.showZanTopTips('手机号输入有误');
        this.setData({
          pickerPhoneFocus: true
        })

        return;
      }
      this.data.pickerInfo.phone = value.pickerPhone;
      this.setData({
        pickerPhoneFocus: false
      })

    }
    // console.log(this.data)
    //send data to sever
    this.setData({submitDisable:true})
    let sendData = {};
    var cardInfo = this.data.lostCardInfo;
    let picker = this.data.pickerInfo;
    sendData = {
      lostCardInfo: {
        'name': cardInfo['name'],
        'cardNum': cardInfo['num'],
        'stuNum': cardInfo['stuNum'],
      },
      pickerInfo: {
        'name': picker.name,
        'phone': picker.phone,
      },
      placeChoice: this.data.placeChoice,
      // cardPlace: this.data.cardPlace,
      way: this.data.way, //作为哪种方式  
      formId: formId,
      pickDate: this.data.pickDate,
      pickerOpenid: app.globalData.openid,
      update:this.data.update,
      oldCardNum:this.data.oldCardNum,
    }
    console.log(sendData)
    var that = this;
    wx.request({
      url: app.globalData.baseUrl + '/pickCardLog',
      method: 'POST',
      data: sendData,
      success: function(res) {
        // var backData=res.data;
        // console.log(res.data)
        if (res.data['isExist'] == 0) {
          if (that.data.way == 0) {
            wx.showModal({
              title: '登记成功',
              icon: 'success',
              content: '已通知失主，请尽快将所拾卡放置在指定的位置',
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          } else {
            wx.showModal({
              title: '登记成功',
              icon: 'success',
              content: '已通知失主，请保持手机畅通',
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }
          // app.hasFit(formId);
        } else if (res.data['isExist'] == 1) {
          // console.log('error');
          wx.showModal({
            title: '',
            icon: 'none',
            content: '拾卡信息已登记，请勿重复登记！',
            showCancel: false,
            success: function() {
              wx.navigateBack({
                delta: 1
              })
            },
          })
        }
        else if (res.data['code'] != undefined) {
          var code=res.data['code']
          if(code == 200){
            wx.showModal({
              title: '',
              // icon: '',
              content: '拾卡信息修改成功',
              showCancel: false,
              success: function () {
                wx.navigateBack({
                  delta: 1
                })
              },
            })
          }
          else if(code == 404){
            
            wx.showModal({
              title: '',
              icon: 'none',
              content: '您的卡已被成功领回，无需修改',
              showCancel: false,
              success: function () {
                wx.navigateBack({
                  delta: 1
                })
              },
            })
          }
          else{
            wx.showToast({              
              // icon: '',
              title: '服务器错误，请稍候再试',              
              success: function () {
                wx.navigateBack({
                  delta: 1
                })
              },
            })
          }
        }
        else {
          // console.log('error');
          wx.showModal({
            title: '错误',
            icon: 'none',
            content: '服务器错误，请稍候再试',
            showCancel: false,
            success: function() {
              wx.navigateBack({
                delta: 1
              })
            },
          })
        }
      },
      fail: function() {

      }
    })
  }
}))